package utils

import (
	"bytes"
	"encoding/binary"
	"encoding/hex"
	"strings"
)

const hextable = "0123456789ABCDEF"

// Join 连接
func Join(src, dst []byte) []byte {
	var ret []byte = make([]byte, len(src))
	copy(ret, src)
	for _, b := range dst {
		ret = append(ret, b)
	}
	return ret
}

//Cs 校验和
func Cs(src []byte) byte {
	var data = 0
	for _, v := range src {
		data += int(v)
	}
	return byte(data)
}

func ClearFE(src []byte) []byte{
	ret := src 
	prefix := []byte{0xFE}
	for {
		if bytes.HasPrefix(ret, prefix) {
			ret = ret[1:]
		} else {
			break 
		}
	}

	return ret 
}

// CRC16
func Crc16(dat []byte) []byte {
	var crc_reg, crc_gen uint32
	crc_reg, crc_gen = 0xFFFF, 0xA001

	for i, l := 0, len(dat); i < l; i++ {
		crc_reg = (uint32(dat[i]) & 0xff) ^ crc_reg
		for j := 8; j > 0; j-- {
			if crc_reg&0x01 == 1 {
				crc_reg >>= 1
				crc_reg ^= crc_gen
			} else {
				crc_reg >>= 1
			}
		}
	}

	buf := make([]byte, 2)
    binary.LittleEndian.PutUint16(buf, uint16(crc_reg))
    return buf
}

func BytesReverse(src []byte) []byte{
	buf := bytes.Buffer{}
	for n, _ := range src {
		buf.WriteByte(src[len(src) - n - 1])
	}
	return buf.Bytes()
}

func BytesToHex(src []byte) string{
	return hex.EncodeToString(src)
}

func HexToBytes(src string) []byte {
	
	return DecodeToBytes(strings.ReplaceAll(src, "-", ""));
}

// DecodeToBytes 字符转字节
func DecodeToBytes(src string) (ret []byte) {
	ret, _ = hex.DecodeString(src)
	return
}

// EncodeToString hex编码 -间隔
func EncodeToString(src []byte) string {
	return EncodeToStringSep(src, byte('-'))
}

// EncodeToStringSep hex编码
func EncodeToStringSep(src []byte, sep byte) string {
	if src == nil || len(src) < 1 {
		return ""
	}

	dst := make([]byte, len(src)*3)
	j := 0
	for _, v := range src {
		dst[j] = hextable[v>>4]
		dst[j+1] = hextable[v&0x0f]
		dst[j+2] = sep
		j += 3
	}
	return string(dst[:len(dst)-1])
}
